package net.ojbk.saishi.action;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.json.JSONObject;

import net.ojbk.saishi.service.sponsorService;

/**
 * Servlet implementation class BackstageServlet
 */
@WebServlet("/BackstageServlet")
public class BackstageServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public BackstageServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=utf-8");
	    response.setCharacterEncoding("utf-8");
		PrintWriter out = response.getWriter();
		HttpSession session=request.getSession();
		// 前奏 ↑
		int type = Integer.parseInt(request.getParameter("type"));
		String matchId = request.getParameter("matchId");
		Map<String,Object>map=new HashMap<String,Object>();
		switch (type) {
		case 1: // 撤销赛事 
			if (sponsorService.revokeOneMatch(matchId) == 1) // 
				map.put("status", true);
			else
				map.put("status", false);
			break;
		case 2: // 修改密码
			String newPw = request.getParameter("newPw");
			int returnCode = sponsorService.modifyPw(matchId, newPw);
			System.out.println(returnCode);
			if (returnCode == 1) // 为反馈其他情况
				map.put("status", true);
			else
				map.put("status", false);
			break;
		case 4: // 立即结束
			if (sponsorService.endMatch(matchId) == 1) // 为反馈其他情况
				map.put("status", true);
			else
				map.put("status", false);
			break;
		}
		// 写出到 json
		JSONObject json=new JSONObject(map); // 转化为 json对象
		out.write(json.toString());
		out.flush();
		System.out.println(json.toString());
	}

}
